//
//  HRFMDBDynamicNotifacationTool.m
//  Hear
//
//  Created by mac on 2017/5/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFMDBDynamicNotifacationTool.h"
#import <FMDB.h>
#import "HRCoverTimeModel.h"
static NSString const *currentUserID = @"currentUserID";
static NSString const *type = @"type";
static NSString const *message = @"message";
static NSString const *content = @"content";
static NSString const *postTime = @"postTime";
static NSString const *fromUserID = @"fromUserID";
static NSString const *messageID = @"messageID";
static NSString const *isRead = @"isRead";
static NSString const *icon = @"icon";
static NSString const *iconColor = @"iconColor";


static NSString const *nickName = @"nickName";

static NSString const *isFriend = @"isFriend";

static HRFMDBDynamicNotifacationTool *tool;

@interface HRFMDBDynamicNotifacationTool ()
@property (nonatomic,strong) FMDatabase *db;

@end
@implementation HRFMDBDynamicNotifacationTool
+(HRFMDBDynamicNotifacationTool *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[HRFMDBDynamicNotifacationTool alloc] init];
    });
    return tool;
}

- (FMDatabase *)db
{
    if (!_db)
    {
        // 1.获得数据库文件的路径
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filename = [doc stringByAppendingPathComponent:@"HearDynamic.sqlite"];
        // 2.得到数据库
        FMDatabase *db = [FMDatabase databaseWithPath:filename];
        // 3.打开数据库
        if ([db open]) {
            // 4.创表
            BOOL result = [db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS HearDynamic (id integer PRIMARY KEY AUTOINCREMENT, %@ text, %@ text, %@ text,%@ text, %@ text, %@ text, %@ text, %@ text, %@ text, %@ text, %@ text, %@ text);",currentUserID,type,message,content,postTime,fromUserID,messageID,isRead,icon,nickName,iconColor,isFriend]];
            if (result) {
                DDLog(@"HRFMDBDynamicNotifacationTool>>>成功创表");
            } else {
                DDLog(@"HRFMDBDynamicNotifacationTool>>>创表失败");
            }
        }
        _db = db;
    }
    return _db;
}

-(void)insertContacts:(HRDynamicNotificationModel *)notiModel
{
    
    // 插入
    NSString *interSql = [NSString stringWithFormat:@"INSERT INTO HearDynamic (%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",currentUserID,type,message,content,postTime,fromUserID,messageID,isRead,icon,nickName,iconColor,isFriend];
    BOOL isInsert = [self.db executeUpdate:interSql,notiModel.currentUserID,notiModel.type,notiModel.message,notiModel.content,notiModel.postTime,notiModel.fromUserID,notiModel.messageID,notiModel.isRead,notiModel.icon,notiModel.nickName,notiModel.iconColor,notiModel.isFriend];
    DDLog(@"----插入数据 ＝ %d",isInsert);
}

-(NSMutableArray *)selectAllContent
{
    NSMutableArray *array = [NSMutableArray array];
    
    // 1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM HearDynamic where currentUserID = ?",USERID];
    
    // 2. 遍历结果
    while ([resultSet next]) {
        NSString *userid = [resultSet stringForColumn:currentUserID];
        if (!userid)
        {
            continue;
        }
        HRDynamicNotificationModel *model = [HRDynamicNotificationModel new];
        model.type = [resultSet stringForColumn:type];
        model.message = [resultSet stringForColumn:message];
        model.content = [resultSet stringForColumn:content];
        model.postTime = [resultSet stringForColumn:postTime];
        model.fromUserID = [resultSet stringForColumn:fromUserID];
        model.messageID = [resultSet stringForColumn:messageID];
        model.ID = [NSString stringWithFormat:@"%d",[resultSet intForColumn:@"id"]];
        model.isRead = [resultSet stringForColumn:isRead];
        model.iconColor = [resultSet stringForColumn:iconColor];

        model.nickName = [resultSet stringForColumn:nickName];
        model.icon = [resultSet stringForColumn:icon];
        model.isFriend = [resultSet stringForColumn:isFriend];

        [array addObject:model];
    }
    
    NSArray* sorted = [array sortedArrayUsingComparator:
                       ^(HRDynamicNotificationModel *obj1, HRDynamicNotificationModel* obj2){
                           NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                           [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm"];
                           NSDate *date1= [dateFormatter dateFromString:obj1.postTime];
                           NSDate *date2= [dateFormatter dateFromString:obj2.postTime];
                           
                           
                           if(date1 == [date1 earlierDate:date2]) {
                               return(NSComparisonResult)NSOrderedDescending;
                           }else {
                               return(NSComparisonResult)NSOrderedAscending;
                           }
                       }];
    return [NSMutableArray arrayWithArray:sorted];
}



-(NSMutableArray *)selectContentOfType:(NSString *)type
{
    NSMutableArray *array = [NSMutableArray array];
    
    // 1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM HearDynamic where currentUserID = ? and type = ?",USERID,type];
    
    // 2. 遍历结果
    while ([resultSet next]) {
        NSString *userid = [resultSet stringForColumn:currentUserID];
        if (!userid)
        {
            continue;
        }
        HRDynamicNotificationModel *model = [HRDynamicNotificationModel new];
        model.type = type;
        model.message = [resultSet stringForColumn:message];
        model.content = [resultSet stringForColumn:content];
        model.postTime = [resultSet stringForColumn:postTime];
        model.fromUserID = [resultSet stringForColumn:fromUserID];
        model.messageID = [resultSet stringForColumn:messageID];
        model.ID = [NSString stringWithFormat:@"%d",[resultSet intForColumn:@"id"]];
        model.isRead = [resultSet stringForColumn:isRead];
        model.iconColor = [resultSet stringForColumn:iconColor];
        
        model.nickName = [resultSet stringForColumn:nickName];
        model.icon = [resultSet stringForColumn:icon];
        model.isFriend = [resultSet stringForColumn:isFriend];
        
        [array addObject:model];
    }
    
    NSArray* sorted = [array sortedArrayUsingComparator:
                       ^(HRDynamicNotificationModel *obj1, HRDynamicNotificationModel* obj2){
                           NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                           [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm"];
                           NSDate *date1= [dateFormatter dateFromString:obj1.postTime];
                           NSDate *date2= [dateFormatter dateFromString:obj2.postTime];
                           
                           
                           if(date1 == [date1 earlierDate:date2]) {
                               return(NSComparisonResult)NSOrderedDescending;
                           }else {
                               return(NSComparisonResult)NSOrderedAscending;
                           }
                       }];
    return [NSMutableArray arrayWithArray:sorted];
}




-(NSInteger)unReadCount:(NSArray *)typeArr
{
    if (typeArr.count){
        NSInteger unReadCount = 0;
        for (NSString *type in typeArr) {

            FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM HearDynamic where currentUserID = ? and type = ?",USERID,type];
            while ([resultSet next]) {
                HRDynamicNotificationModel *model = [HRDynamicNotificationModel new];
                model.isRead = [resultSet stringForColumn:isRead];
                if (![model.isRead intValue])
                {
                    unReadCount ++;
                }

            }

        }
        return unReadCount;

    }else{
        NSInteger unReadCount = 0;

        FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM HearDynamic where currentUserID = ?",USERID];
        while ([resultSet next]) {
            HRDynamicNotificationModel *model = [HRDynamicNotificationModel new];
            model.isRead = [resultSet stringForColumn:isRead];
            if (![model.isRead intValue] )
            {
                unReadCount ++;
            }

        }
        return unReadCount;
    }
    return 0;

}
-(void)updateReadCount:(NSString *)ID{
    NSString *deleteSql = [NSString stringWithFormat:@"UPDATE HearDynamic SET isRead = ? WHERE currentUserID = ? and id = ?"];
    BOOL isupdateReadCount = [self.db executeUpdate:deleteSql,@"1",USERID,ID];
    DDLog(@"");
}

-(BOOL)updateSomeField:(NSString *)name andValue:(NSString *)value andID:(NSString *)ID{
    NSString *deleteSql = [NSString stringWithFormat:@"UPDATE HearDynamic SET %@ = ? WHERE currentUserID = ? and id = ?",name];
    return [self.db executeUpdate:deleteSql,value,USERID,ID];
}


- (BOOL)deleteRequestId:(NSString *)ID
{
    NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM HearDynamic WHERE currentUserID = ? and id = ?"];
    return [self.db executeUpdate:deleteSql,USERID,ID];
    return NO;
}




-(void)dealloc
{
    [self.db close];
    self.db = nil;
}


@end
